package org.jawa.dao.hibernate;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jawa.dao.CategoryDao;
import org.jawa.model.Category;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CategoryDaoHibernate extends HibernateDaoSupport implements
		CategoryDao {
	Log log = LogFactory.getLog(CategoryDaoHibernate.class);

	@SuppressWarnings("unchecked")
	@Override
	public List<Category> getAll() {
		// TODO Auto-generated method stub
		List<Category> list = getHibernateTemplate().find(
				"from Category order by id");
		if (list.isEmpty()) {
			return null;
		} else {
			return list;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Category> getCategories(Long categoryID) {
		// TODO Auto-generated method stub
		List<Category> list = getHibernateTemplate().find(
				"from Category where id=?", categoryID);
		if (list.isEmpty()) {
			return null;
		} else {
			return list;
		}
	}

	@Override
	public void removeCategory(Long categoryID) {
		// TODO Auto-generated method stub
		getHibernateTemplate().delete(getByID(categoryID));
	}

	@Override
	public Category saveCategory(Category category) {
		// TODO Auto-generated method stub
		getHibernateTemplate().saveOrUpdate(category);
		getHibernateTemplate().flush();
		return category;
	}

	@Override
	public Category getByID(Long categoryID) {
		// TODO Auto-generated method stub
		Category category = (Category) getHibernateTemplate().load(
				Category.class, categoryID);
		if (null == category) {
			log.debug("sorry this Id is not exist.");
			throw new ObjectRetrievalFailureException(Category.class,
					categoryID);
		} else {
			return category;
		}
	}

}
